/***************************************************************************
                          shell.cpp  -  description
                             -------------------
    begin                : Sat Aug 24 2002
    copyright            : (C) 2002 by Michiel Visser
    email                : 
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
/* TYLE (TYPE-LESS) Programming language */

#include <stdio.h>
#include "tyle.h"

class BoolVar
{
	bool value, oldvalue;
public:
	BoolVar(bool v): value(v), oldvalue(v) {}
	void set(bool v,bool setOnce) { oldvalue=setOnce?value:v; value=v; }
	bool get() { return value; }
	bool update() { value=oldvalue; }
} tyleOutput(true), toClipboard(true), nullOutput(false);

static bool quit=false;

void hashParser(char *str)
{
	switch ( str[0] )
	{
	  case 'q': quit=true; break;
	  case 'T': tyleOutput.set(true,str[1]=='o'); break;
	  case 't': tyleOutput.set(false,str[1]=='o'); break;
	  case 'N': nullOutput.set(true,str[1]=='o'); break;
	  case 'n': nullOutput.set(false,str[1]=='o'); break;
	  case 'C': toClipboard.set(true,str[1]=='o'); break;
	  case 'c': toClipboard.set(false,str[1]=='o'); break;
	  default: printf("Unknown # command.\n"); break;
  }
}

static void execute(char *instr)
{
	Tyle::Object o(instr);
	if (nullOutput.get() || o.getType()!=TOT_Null)
	{
		Tyle::String *s = tyleOutput.get() ? (Tyle::String *)(new Tyle::TyleOutput(o)) : (Tyle::String *)(new Tyle::TextOutput(o));
		printf("%s\n", (char *)*s );
		if ( toClipboard.get() )
		{
			HANDLE nd;
			LPSTR ns; 
		  nd = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE, s->length()+2);
		  ns = (LPSTR)GlobalLock(nd);
		  strcpy(ns,(char *)*s);
		  GlobalUnlock(nd);
			OpenClipboard(NULL);
		  EmptyClipboard();       
		  SetClipboardData(/*CF_OEMTEXT*/ CF_TEXT, nd); 
		  CloseClipboard(); 
		}
		delete s;
	}
	nullOutput.update();
	tyleOutput.update();
	toClipboard.update();
}

int main(int argc, char **argv)
{
	char *s = new char[10000];
  Tyle_init(hashParser);
	Tyle_stackString(argv[0]);
  for(int i=1; !quit && i<argc; i++)
  { execute(argv[i]);
  }
  while(!quit)
  { printf(">");
    fgets((char *)s,10000, stdin);
    execute(s);
  }
  delete[] s;
	Tyle_quit();
}
